﻿#region << 版 本 注 释 >>
/*----------------------------------------------------------------
 * 创建者：王明亮
 * 创建时间：2023/8/15 14:02:20
 * 版本：V1.0.0
 * 描述：
 *
 * ----------------------------------------------------------------
 * 修改人：
 * 时间：
 * 修改说明：
 *
 * 版本：V1.0.1
 *----------------------------------------------------------------*/
#endregion << 版 本 注 释 >>
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Threading.Tasks;

namespace MyWebApp.Filter
{
    /// <summary>
    /// 结果过滤器
    /// </summary>
    public class MyResultFilter : Attribute, IResultFilter
    {

        #region IResultFilter

        /// <summary>
        ///执行之前
        /// </summary>
        /// <param name="context"></param>
        public void OnResultExecuting(ResultExecutingContext context)
        {
            if (context.Result is JsonResult)
            {
                JsonResult result = (JsonResult)context.Result;

                //进行返回结果进行再次封装
                context.Result = new JsonResult(new
                {
                    Success = true,
                    Message = "Ok",
                    Data = result.Value
                });
            }
        }
        /// <summary>
        ///执行之后
        /// </summary>
        /// <param name="context"></param>
        public void OnResultExecuted(ResultExecutedContext context)
        {
            var  result = context.Result;//拿到Json结果

            Console.WriteLine("在执行之后ResultFilter.OnResultExecuted方法");
        }
        #endregion

        #region IAsyncResultFilter

        /// <summary>
        /// 执行时
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            if (context.Result is JsonResult)
            {
                JsonResult result = (JsonResult)context.Result;
                context.Result = new JsonResult(new
                {
                    Success = true,
                    Message = "Ok",
                    Data = result.Value
                });
            }
            await next.Invoke();
        }
        #endregion
    }
}
